package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    public static void addCookie(HttpServletResponse response,String name,String value,int timeout){
        //把token存到cookie中
        Cookie cookie = new Cookie(name, value);
        //设置请求时cookie中共享的路径,设为所有路径都可以访问
        cookie.setPath("/");
        //设置有效的时间
        cookie.setMaxAge(timeout);
        //响应到浏览器
        response.addCookie(cookie);
    }

    public static String getToken(HttpServletRequest request){
        //请求获取cookies集合
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            //判空
            if (cookie != null){
                //找到存入cookie中token的cookie
                if (cookie.getName().equals("token")){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
